package com.sec.etech.org.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.sec.etech.org.dto.EtechUserDto;
import com.sec.etech.sys.util.DbUtil;
import org.openbpm.base.core.util.BeanCopierUtils;
import org.openbpm.form.util.JdbcTemplateUtil;
import org.openbpm.org.api.model.IUser;
import org.openbpm.org.core.manager.OrgRelationManager;
import org.openbpm.org.core.model.OrgRelation;
import org.openbpm.org.service.impl.DefaultUserService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Primary
@Service("etechUserService")
public class EtechUserService extends DefaultUserService {

    @Resource
    OrgRelationManager orgRelationMananger;

    @Cacheable("userById")
    public IUser getUserById(String userId) {
        EtechUserDto user = null;
        IUser user1 = super.getUserById(userId);
        if(user1!=null){
            user = BeanCopierUtils.transformBean(user1, EtechUserDto.class);
            //补充用户部门信息
            List<OrgRelation> relationList = orgRelationMananger.getUserRelation(user.getUserId(), "userGroup");
            if(CollectionUtil.isNotEmpty(relationList)){
                for(OrgRelation relation: relationList){
                    if(0==relation.getIsMaster()){
                        user.setDprtid(relation.getGroupId());
                        break;
                    }
                }
            }
        }
        return user;
    }

    /**
     * 查询用户信息
     * @param userId
     * @return
     */
    public EtechUserDto getUserInfoById(String userId) {
        JdbcTemplate jdbcTemplate = JdbcTemplateUtil.getJdbcTemplate("dataSourceDefault");
        String sql = "select u.*, g.id_ groupId, g.id_ dprtid, g.name_ dprtName from org_user u,org_relation r,org_group g " +
                " where u.id_=r.user_id_ and r.type_='groupUser' and g.id_=r.group_id_ and r.status_=1 and u.id_=? ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, userId);
        EtechUserDto dto = null;
        if(list!=null && list.size()>0){
            dto = JSONObject.toJavaObject(new JSONObject(list.get(0)), EtechUserDto.class);
        }
        return dto;
    }

    public IUser getUserOnlyById(String userId) {
        IUser user = super.getUserById(userId);
        return user;
    }
    /**
     * 根据用户id查询姓名
     * @param userId
     * @return
     */
    public String getUserNameById(String userId){
        if(userId==null || "0".equals(userId.trim()) || "".equals(userId.trim())){
            return "";
        }
        IUser user = super.getUserById(userId);
        return user!=null? user.getFullname(): "";
    }

    public String getUserNameById(Long userId){
        if(userId==null){
            return "";
        }
        IUser user = super.getUserById(userId.toString());
        return user!=null? user.getFullname(): "";
    }

    public String getUserNameByIds(List<String> userIds){
        if (userIds != null){
            return userIds.stream().map(this::getUserNameById).collect(Collectors.joining(","));
        }else{
            return "";
        }

    }

    @Cacheable("userMailByIdOrAccount")
    public String getUserMailByIdOrAccount(String key){

        String sql = "select email_ as email from org_user where account_ = "+key+" or id_ = " + key +"";
        List<Map<String, Object>> list = DbUtil.getJdbcTemplate().queryForList(sql);
        if(list!=null && !list.isEmpty()){
            return String.valueOf(list.get(0).get("email"));
        }
        return null;
    }
    //根据id查询用户账号
    public String getUserAccountById(String userId) {
        IUser user = this.getUserById(userId);
        return user!=null? user.getAccount(): "";
    }

    /**
     * 通过角色code获取用户ID列表
     * @param roleCode
     * @return
     */
    public List<String> getUserIdsByRoleCode(String roleCode){
        // TODO 处理特殊角色code，比如 manager_tech 技术部门科室主管
        List<String> userIds = new ArrayList<>();
        String sql = "select user_id_\n" +
                "from org_relation r1, org_role role\n" +
                "where r1.type_='userRole' and r1.role_id_=role.id_ and role.alias_='"+roleCode+"'\n" +
                "union\n" +
                "select user_id_\n" +
                "from org_relation r1\n" +
                "where r1.type_='groupUser' \n" +
                "and r1.group_id_ in (\n" +
                "  select group_id_\n" +
                "from org_relation r2, org_role role\n" +
                "where r2.type_='roleGroup' and r2.role_id_=role.id_ and role.alias_='"+roleCode+"'\n" +
                ")";
        List<Map<String,Object>> listUsers = DbUtil.getJdbcTemplate().queryForList(sql);
        if(CollectionUtil.isNotEmpty(listUsers)){
            for(Map<String,Object> row: listUsers){
                userIds.add(MapUtil.getStr(row, "user_id_"));
            }
        }
        return userIds;
    }

    /**
     * 根据部门id集合查询用户
     * @param groupIds
     * @return
     */
    public List<IUser> getUsersByGroupIds(List<String> groupIds) {
        if(groupIds==null || groupIds.size()==0){
            return new ArrayList<>();
        }
        List<IUser> userList = new ArrayList<>();
        String sql = "select u.id_ userId,u.* from org_user u where status_=1 and id_ in " +
                "(select r.user_id_ from org_relation r,org_group g where g.id_= r.group_id_ AND r.type_= 'groupUser' AND r.status_= 1 and g.id_ in ("
                    +String.join(",",groupIds)+ ") )";
        List<Map<String,Object>> listUsers = DbUtil.getJdbcTemplate().queryForList(sql);
        if(listUsers!=null && listUsers.size()>0){
            for(Map<String,Object> map: listUsers){
                userList.add(JSONObject.toJavaObject(new JSONObject(map), IUser.class));
            }
        }
        return userList;
    }

    /**
     * 根据uid批量查询用户信息
     * @param uIds
     * @return
     */
    public Map<String,JSONObject> getUsersByIds(List<String> uIds){
        Map<String,JSONObject> userMap = new HashMap<>();
        String sql = "select u.id_ userId,u.* from org_user u where id_ in ('" +String.join("','",uIds)+ "')";
        List<Map<String,Object>> listUsers = DbUtil.getJdbcTemplate().queryForList(sql);
        if(listUsers!=null && listUsers.size()>0){
            for(Map<String,Object> map: listUsers){
                userMap.put(map.get("userId").toString(),new JSONObject(map));
            }
        }
        return userMap;
    }

    /**
     * 根据用户姓名获取ID
     * @param userName
     * @return
     */
    public Long getUserIdByName(String userName){
        String sql = "select id_ from org_user where fullname_=? order by id_";
        List<Map<String,Object>> list = DbUtil.getJdbcTemplate().queryForList(sql, userName);
        return list!=null && list.size()>0? Long.parseLong(list.get(0).get("id_").toString()): null;
    }
}
